<template>
  <div class="building-container">
    <el-card>
      <div class="management-title">
        <h2>楼栋管理 - {{ plotName }}</h2>
        <el-button @click="goBack" style="margin-left: 16px;">返回小区列表</el-button>
      </div>

      <!-- 小区信息展示 -->
      <div class="plot-info-section" v-if="plotInfo.name">
        <div class="plot-info-card">
          <div class="plot-info-left">
            <div class="plot-info-images" v-if="plotImages.length > 0">
              <img 
                v-for="(image, index) in plotImages.slice(0, 3)" 
                :key="index"
                :src="image" 
                :alt="`小区图片${index + 1}`"
                class="plot-info-img"
                @error="handleImageError"
              />
            </div>
            <div v-else class="no-images">
              <el-icon size="48"><Picture /></el-icon>
              <p>暂无图片</p>
            </div>
          </div>
          
          <div class="plot-info-right">
            <h3 class="plot-info-title">{{ plotInfo.name }}</h3>
            <div class="plot-info-details">
              <div class="info-item">
                <el-icon><LocationFilled /></el-icon>
                <span>{{ plotInfo.address || '地址信息暂无' }}</span>
              </div>
              <div class="info-item" v-if="plotInfo.number">
                <el-icon><Phone /></el-icon>
                <span>{{ plotInfo.number }}</span>
              </div>
              <div class="info-item" v-if="plotInfo.listTime">
                <el-icon><Calendar /></el-icon>
                <span>开盘时间：{{ formatDate(plotInfo.listTime) }}</span>
              </div>
              <div class="info-item" v-if="plotInfo.rentMin && plotInfo.rentMax">
                <el-icon><House /></el-icon>
                <span>租金范围：{{ formatMoney(plotInfo.rentMin) }}~{{ formatMoney(plotInfo.rentMax) }}元/月</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="building-header">
        <el-button type="primary" @click="handleAddBuilding">
          <el-icon><Plus /></el-icon>
          新增楼栋
        </el-button>
        <el-button type="info" @click="handlePlotPlanning">
          <el-icon><Setting /></el-icon>
          小区规划
        </el-button>
      </div>

      <!-- 楼栋网格 -->
      <div class="building-grid" v-loading="loading">
        <div 
          v-for="building in buildingList" 
          :key="building.id"
          class="building-card"
          @click="handleBuildingClick(building)"
        >
          <div class="building-header">
            <h3 class="building-name">{{ building.name }}栋</h3>
            <el-tag :type="building.delFlag === 0 ? 'success' : 'danger'" size="small">
              {{ building.delFlag === 0 ? '正常' : '已删除' }}
            </el-tag>
          </div>
          
          <div class="building-info">
            <div class="info-row">
              <span class="info-label">单元数：</span>
              <span class="info-value">{{ building.unitNum || 0 }}个</span>
            </div>
            <div class="info-row">
              <span class="info-label">楼层数：</span>
              <span class="info-value">{{ building.floorNum || 0 }}层</span>
            </div>
            <div class="info-row">
              <span class="info-label">房屋数：</span>
              <span class="info-value">{{ building.houseNum || 0 }}套</span>
            </div>
          </div>
          
          <div class="building-actions">
            <el-button size="small" type="primary" @click.stop="handleViewDetails(building)">
              房源详情
            </el-button>
            <el-button size="small" type="success" @click.stop="handleManageTypes(building)">
              户型管理
            </el-button>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && buildingList.length === 0" class="empty-building">
          <el-empty description="暂无楼栋数据">
            <el-button type="primary" @click="handleAddBuilding">添加楼栋</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 新增楼栋对话框 -->
      <el-dialog
        title="新增楼栋"
        v-model="showAddDialog"
        width="600px"
        :before-close="handleCancelAdd"
      >
        <el-form
          ref="buildingFormRef"
          :model="buildingForm"
          :rules="buildingFormRules"
          label-width="120px"
        >
          <el-form-item label="楼栋名称" prop="name">
            <el-input v-model="buildingForm.name" placeholder="请输入楼栋名称（如：1、A、甲等）" />
          </el-form-item>
          
          <el-form-item label="单元数量" prop="unitNum">
            <el-input-number 
              v-model="buildingForm.unitNum" 
              :min="1" 
              :max="20"
              @change="handleUnitNumChange"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="楼层数量" prop="floorNum">
            <el-input-number 
              v-model="buildingForm.floorNum" 
              :min="1" 
              :max="100"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="每单元每层户数">
            <div class="floor-user-config">
              <div 
                v-for="(userNum, index) in buildingForm.floorUserNumList" 
                :key="index"
                class="unit-config"
              >
                <span class="unit-label">第{{ index + 1 }}单元：</span>
                <el-input-number 
                  v-model="buildingForm.floorUserNumList[index]" 
                  :min="1" 
                  :max="20"
                  size="small"
                />
                <span class="unit-suffix">户/层</span>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="预计房屋总数">
            <el-input :value="calculateTotalHouses() + '套'" readonly />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCancelAdd">取消</el-button>
            <el-button type="primary" @click="handleConfirmAdd" :loading="submitLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElForm } from 'element-plus';
import { Location, Setting, LocationFilled, House, Calendar, Phone, Plus, Picture } from '@element-plus/icons-vue';
import baseService from "@/service/baseService";

// 类型定义
interface PlotInfo {
  id?: number;
  name?: string;
  address?: string;
  number?: string;
  listTime?: string;
  rentMin?: number;
  rentMax?: number;
  ossUrls?: string;
}

interface Building {
  id: number;
  name: string;
  plotId: number;
  unitNum: number;
  floorNum: number;
  houseNum: number;
  delFlag: number;
}

// 响应式数据
const loading = ref(false);
const buildingList = ref<Building[]>([]);
const plotInfo = ref<PlotInfo>({});
const showAddDialog = ref(false);
const submitLoading = ref(false);
const plotImages = ref([]);

// 表单数据
const buildingForm = reactive({
  name: '',
  unitNum: 1,
  floorNum: 1,
  floorUserNumList: [1]
});

const buildingFormRef = ref<InstanceType<typeof ElForm>>();

// 表单验证规则
const buildingFormRules = {
  name: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  unitNum: [
    { required: true, message: '请输入单元数量', trigger: 'blur' }
  ],
  floorNum: [
    { required: true, message: '请输入楼层数量', trigger: 'blur' }
  ]
};

// 获取URL参数（兼容hash模式）
const getUrlParams = () => {
  const hash = window.location.hash;
  const queryString = hash.includes('?') ? hash.split('?')[1] : window.location.search.substring(1);
  return new URLSearchParams(queryString);
};

const urlParams = getUrlParams();
const plotId = ref(urlParams.get('plotId') || '');
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));
const plotAddress = ref(decodeURIComponent(urlParams.get('plotAddress') || ''));

// 工具函数
const formatDate = (dateStr: string) => {
  if (!dateStr) return '暂无';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

const formatMoney = (amount: number) => {
  if (!amount) return '0';
  return amount.toLocaleString('zh-CN');
};

// 处理小区图片
const processPlotImages = (plot: any) => {
  if (plot.ossUrls) {
    plotImages.value = plot.ossUrls.split(',').filter((url: string) => url.trim());
  } else {
    plotImages.value = [];
  }
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = '';
};

// API调用函数
const getPlotInfo = async () => {
  try {
    const response = await baseService.get(`/rental/areaplot/${plotId.value}`);
    if (response.code === 0) {
      plotInfo.value = response.data || {};
      processPlotImages(plotInfo.value);
    }
  } catch (error) {
    console.error('获取小区信息失败:', error);
  }
};

const getBuildingList = async () => {
  loading.value = true;
  try {
    const response = await baseService.get(`/rental/areabuilding/getBuildingByPlotId/${plotId.value}`);
    if (response.code === 0) {
      buildingList.value = response.data.list || [];
      ElMessage.success(`成功获取 ${buildingList.value.length} 栋楼栋数据`);
    } else {
      ElMessage.error(response.msg || '获取楼栋列表失败');
    }
  } catch (error) {
    console.error('获取楼栋列表失败:', error);
    ElMessage.error('获取楼栋列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

const saveBuildingData = async (data: any) => {
  try {
    const response = await baseService.post('/rental/areabuilding', data);
    if (response.code === 0) {
      ElMessage.success('楼栋添加成功');
      return true;
    } else {
      ElMessage.error(response.msg || '添加楼栋失败');
      return false;
    }
  } catch (error) {
    console.error('添加楼栋失败:', error);
    ElMessage.error('添加楼栋失败，请检查网络连接');
    return false;
  }
};

// 事件处理函数
const goBack = () => {
  window.close();
};

const handleBuildingClick = (building: any) => {
  ElMessage.info(`点击了楼栋: ${building.name}栋`);
  console.log('楼栋信息:', building);
};

const handleViewDetails = (building: any) => {
  // 使用hash模式路由路径
  const url = `#/rental/house-list-details?buildingId=${building.id}&buildingName=${encodeURIComponent(building.name)}&plotName=${encodeURIComponent(plotName.value)}`;
  window.open(url, '_blank');
};

const handleManageTypes = (building: any) => {
  // 使用hash模式路由路径
  const url = `#/rental/type-management?buildingId=${building.id}&buildingName=${encodeURIComponent(building.name)}栋&plotName=${encodeURIComponent(plotName.value)}`;
  window.open(url, '_blank');
};

const handleAddBuilding = () => {
  showAddDialog.value = true;
  resetBuildingForm();
};

const handlePlotPlanning = () => {
  // 使用hash模式路由路径
  const url = `#/rental/plot-planning?plotId=${plotId.value}&plotName=${encodeURIComponent(plotName.value)}&plotAddress=${encodeURIComponent(plotAddress.value || '')}`;
  window.open(url, '_blank');
};

const resetBuildingForm = () => {
  buildingForm.name = '';
  buildingForm.unitNum = 1;
  buildingForm.floorNum = 1;
  buildingForm.floorUserNumList = [1];
  if (buildingFormRef.value) {
    buildingFormRef.value.clearValidate();
  }
};

const handleUnitNumChange = (value: number) => {
  const currentLength = buildingForm.floorUserNumList.length;
  if (value > currentLength) {
    // 增加单元，默认每层1户
    for (let i = currentLength; i < value; i++) {
      buildingForm.floorUserNumList.push(1);
    }
  } else if (value < currentLength) {
    // 减少单元
    buildingForm.floorUserNumList = buildingForm.floorUserNumList.slice(0, value);
  }
};

const calculateTotalHouses = () => {
  return buildingForm.floorUserNumList.reduce((sum, userNum) => sum + userNum * buildingForm.floorNum, 0);
};

const handleCancelAdd = () => {
  showAddDialog.value = false;
  resetBuildingForm();
};

const handleConfirmAdd = async () => {
  if (!buildingFormRef.value) return;

  try {
    await buildingFormRef.value.validate();

    submitLoading.value = true;

    const buildingData = {
      name: buildingForm.name,
      plotId: parseInt(plotId.value || '0'),
      unitNum: buildingForm.unitNum,
      floorNum: buildingForm.floorNum,
      floorUserNumList: [...buildingForm.floorUserNumList]
    };

    const success = await saveBuildingData(buildingData);
    if (success) {
      showAddDialog.value = false;
      resetBuildingForm();
      getBuildingList(); // 重新获取楼栋列表
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  if (!plotId.value) {
    ElMessage.error('缺少小区ID参数');
    return;
  }
  getPlotInfo();
  getBuildingList();
});
</script>

<style scoped>
.building-container {
  display: flex;
  flex-direction: column;
}

.management-title {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.management-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.plot-info-section {
  margin-bottom: 24px;
}

.plot-info-card {
  display: flex;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.plot-info-left {
  width: 200px;
  margin-right: 20px;
  flex-shrink: 0;
}

.plot-info-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.plot-info-img {
  width: 60px;
  height: 45px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.no-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.no-images p {
  margin: 8px 0 0 0;
  font-size: 12px;
}

.plot-info-right {
  flex: 1;
}

.plot-info-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.plot-info-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item .el-icon {
  color: #409eff;
}

.building-header {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.building-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  min-height: 200px;
}

.building-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.building-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.building-card .building-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.building-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.building-info {
  margin-bottom: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #909399;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.building-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.empty-building {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.floor-user-config {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.unit-config {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-label {
  min-width: 80px;
  color: #606266;
  font-size: 14px;
}

.unit-suffix {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .building-grid {
    grid-template-columns: 1fr;
  }

  .plot-info-card {
    flex-direction: column;
  }

  .plot-info-left {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
  }

  .management-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
